package com.tiantianyuegou.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tiantianyuegou.R;
import com.tiantianyuegou.adapter.GouwucheAdapter;
import com.tiantianyuegou.app.SysApplication;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.http.SPHelper;
import com.tiantianyuegou.model.ProductModel;
import com.tiantianyuegou.model.StoreModel;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.Tools;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 购物车
 * Created by huyang on 2016/1/7 0007.
 */
public class GouwucheActivity extends BaseActivity implements View.OnClickListener {
    private TextView tv_gouwuche_sum, tv_gouwuche_freight, tv_gouwuche_operation, tv_AllSelect;
    private ListView gouwuche_list;
    private FrameLayout mFrame_noShopping;
    private LinearLayout mLinear_op;
    private ImageView mImg_AllSelect;
    List<StoreModel> mData;
    private Map<String, Boolean> mLastChoose = new HashMap<>();//保存上次数据
    ArrayList<StoreModel> mTransData;
    GouwucheAdapter mAdapter;
    private boolean isAllSelect = false;

    private LoadingDialog mLoadingDialog;
    private Double mGuanChange;
    private Double mDeduction = 0d;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gouwuche);
        setTitle("购物车");
       Tools.changeSystemBar(this);
        initViews();

        //将activity加入栈
        SysApplication.getInstance().addActivity(this);
    }

    @Override
    public void findViewByIds() {
        tv_gouwuche_sum = (TextView) findViewById(R.id.tv_gouwuche_sum);
        tv_gouwuche_freight = (TextView) findViewById(R.id.tv_gouwuche_freight);
        tv_gouwuche_operation = (TextView) findViewById(R.id.tv_gouwuche_operation);
        gouwuche_list = (ListView) findViewById(R.id.gouwuche_list);
        tv_AllSelect = (TextView) findViewById(R.id.tv_gouwuche_store_txt);
        mImg_AllSelect = (ImageView) findViewById(R.id.iv_gouwuche_store_img);
        mFrame_noShopping = (FrameLayout) findViewById(R.id.shopping_no_shoppingcar);
        mLinear_op = (LinearLayout) findViewById(R.id.confirm_bottom);
    }

    @Override
    public void initListener() {
        tv_gouwuche_operation.setOnClickListener(this);
        tv_AllSelect.setOnClickListener(this);
        mImg_AllSelect.setOnClickListener(this);
        gouwuche_list.setVisibility(View.GONE);
        mFrame_noShopping.setVisibility(View.VISIBLE);
        mLinear_op.setVisibility(View.GONE);
    }

    @Override
    public void initData() {
        mLoadingDialog = new LoadingDialog(this);
        mData = new ArrayList<>();
        mTransData = new ArrayList<>();
        mAdapter = new GouwucheAdapter(this);
        gouwuche_list.setAdapter(mAdapter);

        //合计价格
        mAdapter.setSelectCouponListener(new GouwucheAdapter.ISelectCouponListener() {
            @Override
            public void reCalcuate(List<StoreModel> mData) {
                reCount(mData);
                changeAllSelect();
            }

            @Override
            public void deleteProduct(int position, ProductModel model) {
                mLoadingDialog.show();
                deleteShoppingCar(position, model);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mAdapter != null) {
            mLastChoose.putAll(mAdapter.getChoose());
        }
        mLoadingDialog.show();
        getShoppingCarList();
    }

    //判断是否改变全选状态
    private void changeAllSelect() {
        boolean allSelect = true;
        for (int i = 0; i < mData.size(); i++) {
            if (mData.get(i).isSelect()) {
                continue;
            } else {
                allSelect = false;
                isAllSelect = false;
                break;
            }
        }
        if (allSelect) {
            isAllSelect = true;
            mImg_AllSelect.setImageResource(R.mipmap.select_icon);
        } else {
            isAllSelect = false;
            mImg_AllSelect.setImageResource(R.mipmap.unselect_icon);
        }
    }


    //重新计算价格
    private void reCount(List<StoreModel> mData) {
        Double productValue = 0d;
        mTransData.clear();
        for (int i = 0; i < mData.size(); i++) {
            mDeduction = 0d;
            List<ProductModel> products = mData.get(i).getProductModels();
            StoreModel storeModel = new StoreModel();
            List<ProductModel> productmodels = new ArrayList<>();
            for (int j = 0; j < products.size(); j++) {
                if (products.get(j).isSelect()) {
                    Integer num = Integer.valueOf(products.get(j).getNumber());
                    Double value = Double.valueOf(products.get(j).getPrice().substring(1));
                    productValue += (num * value);
                    productmodels.add(products.get(j));
                    storeModel.setStoreId(mData.get(i).getStoreId());
                    storeModel.setStoreName(mData.get(i).getStoreName());
                    storeModel.setUnitPrice(mData.get(i).getUnitPrice());
                    mDeduction += Double.valueOf(products.get(j).getCanUseGuan());
                }
            }
            if (productmodels.size() > 0) {
                storeModel.setProductModels(productmodels);
                //设置运费和贯抵现值（确认订单界面使用）
                //当个人的总贯数小于该店铺中的总贯数的时候，可用贯显示我的总贯数
                if (mDeduction > Integer.valueOf(SPHelper.getTmGuanCount())) {
                    storeModel.setCanUseGuan(SPHelper.getTmGuanCount());
                } else {
                    storeModel.setCanUseGuan(new DecimalFormat("0").format(mDeduction));
                }
                // Log.e("TAG","can use guan :"+mDeduction);
                storeModel.setExpress("0.00");
                storeModel.setTotalGuan(SPHelper.getTmGuanCount());
                mTransData.add(storeModel);//添加选中的店铺的商品
            }
        }
        tv_gouwuche_sum.setText("￥" + new DecimalFormat("0.00").format(productValue));
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_gouwuche_store_img:
            case R.id.tv_gouwuche_store_txt:
                if (!isAllSelect) {//全选
                    isAllSelect = true;
                    mImg_AllSelect.setImageResource(R.mipmap.select_icon);
                    for (int i = 0; i < mData.size(); i++) {
                        mData.get(i).setIsSelect(true);
                        for (int j = 0; j < mData.get(i).getProductModels().size(); j++) {
                            mData.get(i).getProductModels().get(j).setIsSelect(true);
                            mLastChoose.put("p" + mData.get(i).getProductModels().get(j).getTscId(), true);
                        }
                        mLastChoose.put("s" + mData.get(i).getStoreId(), true);
                    }
                    reCount(mData);
                } else {//取消全选
                    isAllSelect = false;
                    mImg_AllSelect.setImageResource(R.mipmap.unselect_icon);
                    for (int i = 0; i < mData.size(); i++) {
                        mData.get(i).setIsSelect(false);
                        for (int j = 0; j < mData.get(i).getProductModels().size(); j++) {
                            mData.get(i).getProductModels().get(j).setIsSelect(false);
                            mLastChoose.put("p" + mData.get(i).getProductModels().get(j).getTscId(), false);
                        }
                        mLastChoose.put("s" + mData.get(i).getStoreId(), false);
                    }
                    reCount(mData);
                }
                mAdapter.notifyDataSetChanged();
                break;
            //結算
            case R.id.tv_gouwuche_operation:
                // reCount(mData);
                if (mTransData.size() > 0) {
                    // Log.e("TAG", "shoppingCar size is:" + mTransData.size());
                    Intent intent = new Intent();
                    intent.putExtra("mTransData", mTransData);
                    intent.putExtra("type", "account");
                    intent.putExtra("whereIn", "1");
                    intent.putExtra("unitPrice", new DecimalFormat("0.00").format(1 / mGuanChange));
                    intent.setClass(GouwucheActivity.this, ConfirmOrderActivity.class);
                    startActivity(intent);
                } else {
                    Toast.makeText(GouwucheActivity.this, "请选择购物商品", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    //获取购物车列表
    private void getShoppingCarList() {
        RequestParams params = new RequestParams();
//        params.addBodyParameter("tmId", SPHelper.getTmId());
        params.addBodyParameter("tmId",342+"");
        params.addBodyParameter("page",1+"");
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.CAR_LIST, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                mLoadingDialog.dismiss();
                Log.e("TAG", "getShoppingCarList response:" + responseInfo.result);
                if (TextUtils.isEmpty(responseInfo.result)) {
                    showMsg("获取购物车列表失败");
                } else {
                    try {
                        JSONObject root = new JSONObject(responseInfo.result);
                        String code = root.getString("code");
                        if ("100".equals(code)) {
                            mLinear_op.setVisibility(View.VISIBLE);
                            mFrame_noShopping.setVisibility(View.GONE);
                            gouwuche_list.setVisibility(View.VISIBLE);
                            mGuanChange = root.getDouble("guanChange");
                            JSONArray list = root.getJSONArray("list");
                            if (list.length() > 0) {
                                mData.clear();
                                for (int i = 0; i < list.length(); i++) {
                                    JSONObject store = list.getJSONObject(i);
                                    StoreModel storeModel = new StoreModel();
                                    storeModel.setStoreId(store.getInt("tmc_id"));
                                    storeModel.setStoreName(store.getString("tmc_good_name"));
//                                    storeModel.setUnitPrice(String.valueOf(new DecimalFormat("0.00").format(1 / mGuanChange)));//贯抵现比例
                                    List<ProductModel> productModels = new ArrayList<ProductModel>();
                                    JSONArray products = store.getJSONArray("products");
                                    for (int j = 0; j < products.length(); j++) {
                                        JSONObject product = products.getJSONObject(j);
                                        ProductModel productModel = new ProductModel();
                                        productModel.setId(product.getInt("tpId"));
                                        productModel.setTscId(product.getInt("tscId"));
                                        Double guan = product.getDouble("tpDeduction");
                                        productModel.setCanUseGuan(new DecimalFormat("0").format(guan * mGuanChange));
                                        //判断是否被勾选
                                        if (mLastChoose.size() > 0) {
                                            if (mLastChoose.containsKey("p" + productModel.getTscId())) {
                                                productModel.setIsSelect(mLastChoose.get("p" + productModel.getTscId()));
                                            }
                                        }
                                        productModel.setName(product.getString("tpName"));
                                        String pic = product.getString("tpPic");
                                        if (pic.contains(",")) {
                                            productModel.setUrl(pic.substring(0, pic.indexOf(",")));
                                        } else {
                                            productModel.setUrl(pic);
                                        }
                                        Double price = Double.valueOf(product.getString("tscPrice"));
                                        productModel.setPrice("￥" + new DecimalFormat("0.00").format(price));
                                        productModel.setNumber(product.getInt("tscCount") + "");
                                        JSONArray spec = product.getJSONArray("spec");
                                        StringBuffer specIds = new StringBuffer();
                                        StringBuffer specValueIds = new StringBuffer();
                                        StringBuffer specStr = new StringBuffer();
                                        if (spec.length() > 0) {
                                            for (int k = 0; k < spec.length(); k++) {
                                                JSONObject specValue = spec.getJSONObject(k);
                                                specIds.append(specValue.getInt("tcsSpecId")).append(",");
                                                specValueIds.append(specValue.getInt("tcsSpecValueId")).append(",");
                                                specStr.append(specValue.getString("tsName")).append(":")
                                                        .append(specValue.getString("tpsSpecValue")).append("  ");
                                                productModel.setStore(Integer.parseInt(specValue.getString("tpsStore")));
                                            }

                                            productModel.setSepecValueIds(specValueIds.substring(0, specValueIds.length() - 1));
                                            productModel.setSpecIds(specIds.substring(0, specIds.length() - 1));
                                            productModel.setSpec(specStr.toString());
                                        }
                                        productModels.add(productModel);
                                    }
                                    //判断是否被勾选
                                    if (mLastChoose.size() > 0) {
                                        if (mLastChoose.containsKey("s" + storeModel.getStoreId())) {
                                            storeModel.setIsSelect(mLastChoose.get("s" + storeModel.getStoreId()));
                                        }
                                    }
                                    storeModel.setProductModels(productModels);
                                    mData.add(storeModel);
                                    mAdapter.setData(mData);
                                    reCount(mData);
                                    mImg_AllSelect.setBackgroundResource(R.mipmap.unselect_icon);
                                    mAdapter.notifyDataSetChanged();
                                }
                            } else {
                                gouwuche_list.setVisibility(View.GONE);
                                mFrame_noShopping.setVisibility(View.VISIBLE);
                                mLinear_op.setVisibility(View.GONE);
                            }
                        } else {
                            showMsg("获取购物车列表失败");
                            gouwuche_list.setVisibility(View.GONE);
                            mFrame_noShopping.setVisibility(View.VISIBLE);
                            mLinear_op.setVisibility(View.GONE);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        gouwuche_list.setVisibility(View.GONE);
                        mFrame_noShopping.setVisibility(View.VISIBLE);
                        mLinear_op.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                mLoadingDialog.dismiss();
                Log.e("TAG", "request failure :" + s);
                showMsg("当前网络不可用，请检查您的网设置");
                gouwuche_list.setVisibility(View.GONE);
                mFrame_noShopping.setVisibility(View.VISIBLE);
                mLinear_op.setVisibility(View.GONE);
            }
        });
    }

    //删除购物车
    private void deleteShoppingCar(final int position, final ProductModel model) {

        RequestParams params = new RequestParams();
        params.addBodyParameter("tmcId", model.getTscId() + "");
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.DELTE_CAR, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                mLoadingDialog.dismiss();
                Log.e("TAG", "delete shopping car response:" + responseInfo.result);
                if (TextUtils.isEmpty(responseInfo.result)) {
                    showMsg("删除商品失败");
                } else {
                    try {
                        JSONObject root = new JSONObject(responseInfo.result);
                        String code = root.getString("code");
                        if ("100".equals(code)) {
                            mData.get(position).getProductModels().remove(model);
                            if (mData.get(position).getProductModels().size() == 0) {
                                mData.remove(position);
                                if (mData.size() == 0) {
                                    gouwuche_list.setVisibility(View.GONE);
                                    mFrame_noShopping.setVisibility(View.VISIBLE);
                                    mLinear_op.setVisibility(View.GONE);
                                }
                            }
                            showMsg("删除成功");
                            mAdapter.notifyDataSetChanged();
                        } else {
                            String msg = root.getString("message");
                            showMsg(msg);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        showMsg("解析失败");
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                mLoadingDialog.dismiss();
                Log.e("TAG", "request failure :" + s);
                showMsg("当前网络不可用，请检查您的网设置");
            }
        });
    }
}
